package com.springboot.controller;

import com.springboot.annotation.RequireRole;
import com.springboot.common.Result;
import com.springboot.service.ICartService;
import com.springboot.utils.JwtTokenUtils;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 购物车表 前端控制器
 * </p>
 *
 * @author zjb
 * @since 2025-10-30
 */
@RestController
@RequestMapping("/cart")
public class CartController {

    @Resource
    private ICartService cartService;

    /**
     * 添加商品到购物车
     *
     * @param productId 商品ID
     * @param skuId     SKU ID（可为空）
     * @param quantity  数量
     * @return 添加结果
     */
    @PostMapping("/add")
    public Result addToCart(@RequestParam Integer productId,
                            @RequestParam(required = false) Integer skuId,
                            @RequestParam Integer quantity) {
        Integer userId = JwtTokenUtils.getCurrentUser().getUserId();
        return cartService.addToCart(userId, productId, skuId, quantity);
    }

    /**
     * 获取用户购物车
     *
     * @return 购物车信息
     */
    @GetMapping("/list")
    public Result getCart() {
        Integer userId = JwtTokenUtils.getCurrentUser().getUserId();
        return cartService.getCart(userId);
    }

    /**
     * 更新购物车项数量
     *
     * @param cartId   购物车项ID
     * @param quantity 数量
     * @return 更新结果
     */
    @PutMapping("/{cartId}")
    public Result updateQuantity(@PathVariable Integer cartId,
                                 @RequestParam Integer quantity) {
        Integer userId = JwtTokenUtils.getCurrentUser().getUserId();
        return cartService.updateQuantity(userId, cartId, quantity);
    }

    /**
     * 删除购物车项
     *
     * @param cartId 购物车项ID
     * @return 删除结果
     */
    @DeleteMapping("/{cartId}")
    public Result deleteCartItem(@PathVariable Integer cartId) {
        Integer userId = JwtTokenUtils.getCurrentUser().getUserId();
        return cartService.deleteCartItem(userId, cartId);
    }

    /**
     * 切换购物车项选中状态
     *
     * @param cartId 购物车项ID
     * @return 切换结果
     */
    @PutMapping("/{cartId}/check")
    public Result toggleCheck(@PathVariable Integer cartId) {
        Integer userId = JwtTokenUtils.getCurrentUser().getUserId();
        return cartService.toggleCheck(userId, cartId);
    }

    /**
     * 批量切换购物车项选中状态
     *
     * @param cartIds 购物车项ID列表
     * @param checked 选中状态：1-选中，0-未选中
     * @return 切换结果
     */
    @PutMapping("/batchCheck")
    public Result batchToggleCheck(@RequestParam Integer[] cartIds,
                                   @RequestParam Integer checked) {
        Integer userId = JwtTokenUtils.getCurrentUser().getUserId();
        return cartService.batchToggleCheck(userId, cartIds, checked);
    }

    /**
     * 清空用户购物车
     *
     * @return 清空结果
     */
    @DeleteMapping("/clear")
    public Result clearCart() {
        Integer userId = JwtTokenUtils.getCurrentUser().getUserId();
        return cartService.clearCart(userId);
    }
}